const os = require('os');

exports.getSys = (req, res) => {
    // 设置响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');



    // 发送初始数据
    sendStatus(res);

    // 定时发送数据
    const timer = setInterval(() => {
        sendStatus(res);
    }, 3000);

    // 监听关闭事件
    req.on('close', () => {
        clearInterval(timer);
        res.end();
    });
};

exports.getIp = (req, res) => {
    let ipAddress;
    let forwardedIpsStr = req.header('x-forwarded-for');
    if (forwardedIpsStr) {
        let forwardedIps = forwardedIpsStr.split(',');
        ipAddress = forwardedIps[0];
    }
    if (!ipAddress) {
        ipAddress = req.connection.remoteAddress;
    }
    res.sd(ipAddress);
}

exports.getTime = (req, res) => {
    try {
        let time = getUptime();

    } catch {
        res.sd("10天")
    }
}

// 发送服务器状态数据
function sendStatus(res) {
    const cpuUsage = Math.round(os.loadavg()[0] * 100);
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    const usedMem = Math.round((totalMem - freeMem) / totalMem * 100);
    const time = getUptime();

    // 将服务器状态数据转换为 JSON 格式并发送给客户端
    const status = {
        cpuUsage,
        usedMem,
        usage: 61,
        time
    };
    res.write(`data: ${JSON.stringify(status)}\n\n`);
}

// 开机时间
function getUptime() {
    const uptime = os.uptime();

    const days = Math.floor(uptime / 86400);
    const hours = Math.floor((uptime % 86400) / 3600);
    const minutes = Math.floor((uptime % 3600) / 60);
    const seconds = Math.floor(uptime % 60);

    return `${days}天${hours}小时${minutes}分钟${seconds}秒`;
}